package com.config;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.*;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.ByteBuffer;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author czw
 */
@Service
public class MyHandler extends TextWebSocketHandler {

    /**
     * 在线用户列表
     */
    private static ConcurrentHashMap<String, List<WebSocketSession>> onlineUserMap = new ConcurrentHashMap<>();
    /**
     * 用户标识
     */
    private static final String CLIENT_ID = "userId";

    /**
     * 用户标识
     */
    private static final String PING = "ping_200";

    private final Object lock = new Object();


    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("成功建立连接");
        synchronized(this.lock) {
            String uid = (String) session.getAttributes().get(CLIENT_ID);
            List<WebSocketSession> userSessions = onlineUserMap.get(uid);
            if (userSessions == null) {
                userSessions = new ArrayList<>();
                onlineUserMap.put(uid, userSessions);
            }
            userSessions.add(session);
        }
    }

    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) {
        String payload = message.getPayload();
        String pin = "";
        try {
            pin = URLDecoder.decode(payload, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (PING.equals(pin)) {
            System.out.println("服务器收到来自sessionId【" + session.getId() + "】的ping消息：【" + payload + "】");
            sendToMy(session,new TextMessage("200_ok"));
        }else{
            if (payload instanceof String) {
                System.out.println("服务器收到来自sessionId【" + session.getId() + "】的信息：【" + payload + "】");
               // sendMessageToAllUsers(message);
                JSONObject jsonObject = JSON.parseObject(payload);
                sendMessageToUser((String)jsonObject.get("toUserId"),message);
            }
        }
    }

    /**
     * 发送信息给指定用户
     * @param clientId
     * @param message
     * @return
     */
    public boolean sendMessageToUser(String clientId, TextMessage message) {
        List<WebSocketSession> webSocketSessions = onlineUserMap.get(clientId);
        webSocketSessions.forEach(session->{
            if (session.isOpen()){
                try {
                    session.sendMessage(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        return true;
    }
    public boolean sendToMy(WebSocketSession session, TextMessage message){
        boolean flag = true;
        try {
            session.sendMessage(message);
        } catch (IOException e) {
            e.printStackTrace();
            flag = false;
        }
        return flag;
    }

    /**
     * 广播信息
     * @param message
     * @return
     */
    public boolean sendMessageToAllUsers(WebSocketMessage message) {
        final boolean[] allSendSuccess = {true};
        System.out.println(onlineUserMap);
        onlineUserMap.forEach((k,v)-> v.forEach((WebSocketSession session)->{
            if (session.isOpen()) {
                try {
                    session.sendMessage(message);
                } catch (IOException e) {
                    e.printStackTrace();
                    allSendSuccess[0] = false;
                }
            }
        }));
        return allSendSuccess[0];
    }


    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        if (session.isOpen()) {
            session.close();
        }
        System.out.println("连接出错");
      //  users.remove(getClientId(session));
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        System.out.println("连接已关闭：" + status);
      //  users.remove(getClientId(session));
    }

//    @Override
//    public boolean supportsPartialMessages() {
//        return false;
//    }
//

    private void removeSessionId(){

    }

}
